package com.rljk.common.filter;


import com.rljk.common.result.CodeMsg;
import com.rljk.exception.GlobalException;
import com.rljk.redis.RedisService;
import com.rljk.service.UserManager;
import com.rljk.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:   YASUO
 * Date:     2018/7/18 14:31
 * Description:
 */
@Slf4j
//@Component
@WebFilter(filterName = "RequestFilter",urlPatterns = "/*")
public class RequestFilter implements Filter {

    //@Resource(name = "userService")
    private UserManager userService;

    //@Autowired
    private RedisService redisService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext sc = filterConfig.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);

        if(cxt != null && cxt.getBean("userService") != null && userService != null){
            userService = (UserManager) cxt.getBean("usersService");
        }if(cxt != null && cxt.getBean("redisService") != null && redisService != null){
            redisService = (RedisService) cxt.getBean("redisService");
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("=====过滤器开始过滤=======");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getParameter("TOKEN");
        if(Tools.notEmpty(token)){
            log.info("token:"+token);
            //1.获取用户信息
            String USER_ID = redisService.get(token);
            log.info("USER_ID:"+USER_ID);
            Map<String, Object> extraParams = new HashMap<String, Object>();
            extraParams.put("USER_ID", USER_ID);
            //利用原始的request对象创建自己扩展的request对象并添加自定义参数
            RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request);
            requestParameterWrapper.addParameters(extraParams);
            filterChain.doFilter(requestParameterWrapper, servletResponse);
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
